package gui;

import getData.GetDataFromProjectXML;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.Collections;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;

import projects.DoOperationsWithProjects;
import projects.WriteGroupsToXMLwithProjects;
import configuration.BaseOperations;


public class ProjectsAndFramesList extends javax.swing.JFrame {

   	private static final long serialVersionUID = -8952565724682019543L;
	static List<String> listOfProjectsForOperations; 
    private static String[] listofProjectsInFrame;
    private static String[] listofFramesInFrame;
	protected static String listOfProjectsFileName;
	protected static String listOfFramesFileName;
	protected static String value = null;
	protected static List<String> listOfProjects;
	protected static int quantityOfProjectsinList;
	protected static List<String> listOfFrames;
	protected static int quantityOfFramesinList;
	protected static String nameOfNewProject;
	protected static int indexOfProjectToDelete = 0;
	private int indexOfProjectToShowFrames;
	private String nameOfProjectToShowFrames;
	private List<String> listOfProjectsWithOldNames;
	private String[] listOfFramesForEditedProject;
	private int indexOfFrameToDelete;
	
    public ProjectsAndFramesList() {
        initComponents();
       
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jListProjects = new javax.swing.JList();
        jLabelProjects = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jListFrames = new javax.swing.JList();
        jLabelFrames = new javax.swing.JLabel();
        jButtonAddProject = new javax.swing.JButton();
        jButtonDeleteProject = new javax.swing.JButton();
        jButtonShowFramesOfProject = new javax.swing.JButton();
        jButtonEditProject = new javax.swing.JButton();
        jButtonAddFrame = new javax.swing.JButton();
        jButtonDeleteFrame = new javax.swing.JButton();
        jButtonViewFrame = new javax.swing.JButton();
        jButtonEditFrame = new javax.swing.JButton();
        jTextFieldNewProjectName = new javax.swing.JTextField();
        jTextFieldNewFrameName = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        
        
        setTitle ("List of projects ond frames");
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        updateDataAtJListProjects();
        
        jScrollPane1.setViewportView(jListProjects);

        jLabelProjects.setText("List of projects");

        JList jlist = new JList(listofProjectsInFrame);
        JScrollPane scrollPane1 = new JScrollPane(jlist);
        jListProjects.add(scrollPane1, BorderLayout.CENTER);

        jScrollPane2.setViewportView(jListFrames);

        //jLabelFrames.setText("Choose project to display frames");

        jButtonAddProject.setText("+");
        jButtonAddProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddProjectActionPerformed(evt);
            }
        });

        jButtonDeleteProject.setText("-");
        jButtonDeleteProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtondeleteProjectActionPerformed(evt);
            }
        });

        jButtonShowFramesOfProject.setText("Show frames");
        jButtonShowFramesOfProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonShowFramesOfProjectActionPerformed(evt);
            }
        });
      
        jButtonEditProject.setText("Edit project");
        jButtonEditProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jButtonEditProjectActionPerformed(evt);
            }
        });

        jButtonAddFrame.setText("+");
        jButtonAddFrame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddFramesActionPerformed(evt);
            }
        });

        jButtonDeleteFrame.setText("-");
        jButtonDeleteFrame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteFramesActionPerformed(evt);
            }
        });
        
        jButtonEditFrame.setText("Edit frame");
        jButtonEditFrame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEditFramesActionPerformed(evt);
            }
        });
        
        jButtonViewFrame.setText("View frame");
        jButtonViewFrame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonViewFrameActionPerformed(evt);
            }
        });
        
        jTextFieldNewProjectName.setText("New project");
        jTextFieldNewFrameName.setText("New frame");
  
        //set default selection
        jListProjects.setSelectedIndex(0);
        jButtonShowFramesOfProjectActionPerformed(null);
        
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jTextFieldNewProjectName)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabelProjects)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jButtonAddProject, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonDeleteProject, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(4, 4, 4)
                        .addComponent(jButtonShowFramesOfProject, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonEditProject, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButtonAddFrame, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonDeleteFrame, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonEditFrame, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonViewFrame, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jSeparator2)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabelFrames)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jTextFieldNewFrameName)
                    .addComponent(jScrollPane2))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelProjects)
                    .addComponent(jLabelFrames))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldNewProjectName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldNewFrameName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAddProject)
                    .addComponent(jButtonDeleteProject)
                    .addComponent(jButtonShowFramesOfProject)
                    .addComponent(jButtonEditProject)
                    .addComponent(jButtonAddFrame)
                    .addComponent(jButtonDeleteFrame)
                    .addComponent(jButtonEditFrame)
                    .addComponent(jButtonViewFrame))
                .addContainerGap())
        );

        pack();
    }

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void updateDataAtJListProjects() {
		jListProjects.setModel(new javax.swing.AbstractListModel() {
          	private static final long serialVersionUID = 6176247245553205046L;
			public int getSize() { return listofProjectsInFrame.length; }
            public Object getElementAt(int i) { return listofProjectsInFrame[i]; }
        });
	}

    @SuppressWarnings({ "rawtypes", "unchecked" })
	private void updateDataAtJListFrames() {
    	jListFrames.setModel(new javax.swing.AbstractListModel() {
         	private static final long serialVersionUID = -7607602573046869991L;
			public int getSize() { return listofFramesInFrame.length; }
            public Object getElementAt(int i) { return listofFramesInFrame[i]; }
        });
	}
	
    @SuppressWarnings("unused")
	private void jButtonAddProjectActionPerformed(java.awt.event.ActionEvent evt) {
        nameOfNewProject = jTextFieldNewProjectName.getText();
    	boolean endButtonProcedureForAdding = DoOperationsWithProjects.addProject(nameOfNewProject,listOfProjectsFileName);
		//System.out.println(endButtonProcedureForAdding);
    	listofProjectsInFrame = listOfProjects.toArray(new String[listOfProjects.size()]);
		updateDataAtJListProjects();
    }

    private void jButtondeleteProjectActionPerformed(java.awt.event.ActionEvent evt) {
    	indexOfProjectToDelete = jListProjects.getSelectedIndex();
    	//System.out.println("Get index " + indexOfProjectToDelete);
    	DoOperationsWithProjects.deleteProject(indexOfProjectToDelete, listOfProjectsFileName);
    	listofProjectsInFrame = listOfProjects.toArray(new String[listOfProjects.size()]);
    	updateDataAtJListProjects();
    }
   
	private void jButtonEditProjectActionPerformed(java.awt.event.ActionEvent evt) {
    	indexOfProjectToDelete = jListProjects.getSelectedIndex();
    	String nameOfProjectToDelete = (String) jListProjects.getSelectedValue();
        nameOfNewProject = jTextFieldNewProjectName.getText();
        boolean endButtonProcedureForEditing = false;
        endButtonProcedureForEditing = DoOperationsWithProjects.checkForDuplicateProject(nameOfNewProject, endButtonProcedureForEditing);
        if (endButtonProcedureForEditing == false){
        	//System.out.println("listOfProjectsFileName 1 " + listOfProjectsFileName);
        	listOfFramesForEditedProject = DoOperationsWithProjects.getListOfFramesForChoosedProject
        		(listOfProjects, listOfProjectsFileName, nameOfProjectToDelete, listOfFrames, listOfFramesForEditedProject);
        	jButtondeleteProjectActionPerformed(evt);
			jButtonAddProjectActionPerformed(evt);
			WriteGroupsToXMLwithProjects.addListOfFramesToProjectAtXML
				(listOfProjects, listOfFrames, listOfProjectsFileName, nameOfNewProject, listOfFramesForEditedProject);
        }
	}
	
	 private void jButtonShowFramesOfProjectActionPerformed(java.awt.event.ActionEvent evt) {
	 	setIndexOfProjectToShowFrames(jListProjects.getSelectedIndex());
	 	nameOfProjectToShowFrames = (String) jListProjects.getSelectedValue();
	 	if (nameOfProjectToShowFrames != null){
	 	listOfFrames = GetDataFromProjectXML.getOldListOfFramesInCurrentProject(nameOfProjectToShowFrames, listOfProjectsFileName);
	 	Collections.sort(listOfFrames);
	 	//System.out.println(listOfFrames);
	 	listofFramesInFrame = listOfFrames.toArray(new String[listOfFrames.size()]);
	 	//System.out.println(listofFramesInFrame);
	 	updateDataAtJListFrames();
	 	jLabelFrames.setText("List of frames for project '" + nameOfProjectToShowFrames + "' :");
	 	//jLabelFrames.setFont(new Font("default", Font.BOLD, 12));
	 	}
	 	else {JOptionPane.showMessageDialog(new JFrame(), "Please, select one of the projects", "Error",
		        JOptionPane.ERROR_MESSAGE);}
	 }
	 
	 protected void jButtonAddFramesActionPerformed(ActionEvent evt) {
		if (nameOfProjectToShowFrames != null){
			boolean endButtonProcedureForEditing = false;
			String nameOfNewFrame = jTextFieldNewFrameName.getText();
			endButtonProcedureForEditing = DoOperationsWithProjects.checkForDuplicateFrame(nameOfNewFrame, endButtonProcedureForEditing);
		    if (endButtonProcedureForEditing == false){
			addFrameToListOfFrames(nameOfNewFrame);
		   	} 
		} else   JOptionPane.showMessageDialog(new JFrame(), "Please, select one of the projects", "Error",
		        JOptionPane.ERROR_MESSAGE);
	 }

		protected void jButtonDeleteFramesActionPerformed(ActionEvent evt) {
			if (nameOfProjectToShowFrames != null){
			deleteFrameFromListOfFrames();
	    	        
			}else   JOptionPane.showMessageDialog(new JFrame(), "Please, select one of the projects", "Error",
			        JOptionPane.ERROR_MESSAGE);
		}

		protected void jButtonEditFramesActionPerformed(ActionEvent evt) {
		if (nameOfProjectToShowFrames != null){
			boolean endButtonProcedureForEditing = false;
			String nameOfNewFrame = jTextFieldNewFrameName.getText();
			endButtonProcedureForEditing = DoOperationsWithProjects.checkForDuplicateFrame(nameOfNewFrame, endButtonProcedureForEditing);
		    if (endButtonProcedureForEditing == false){
		    	deleteFrameFromListOfFrames();
		    	addFrameToListOfFrames(nameOfNewFrame);
		   	} 
		} else   JOptionPane.showMessageDialog(new JFrame(), "Please, select one of the projects", "Error",
		        JOptionPane.ERROR_MESSAGE);
		}
	
		protected void jButtonViewFrameActionPerformed(ActionEvent evt) {
		new FieldsInFrames();
		String nameOfFrameToView= (String)jListFrames.getSelectedValue();
		//
		//
		//	newFrame.main(nameOfFrameToView);
		//
		//
		}
	
		private void addFrameToListOfFrames(String nameOfNewFrame) {
		listOfFrames.add(nameOfNewFrame);
		Collections.sort(listOfFrames);
		listofFramesInFrame = listOfFrames.toArray(new String[listOfFrames.size()]);
		updateDataAtJListFrames();
//	System.out.println(listOfFrames);
//	System.out.println(listofFramesInFrame);
		WriteGroupsToXMLwithProjects.addListOfFramesToProjectAtXML
		(listOfProjects, listOfFrames, listOfProjectsFileName, 
				nameOfProjectToShowFrames, listofFramesInFrame);
		}

		private void deleteFrameFromListOfFrames() {
		indexOfFrameToDelete = jListFrames.getSelectedIndex();
		setNameOfFrameToDelete((String) jListFrames.getSelectedValue());
		String checkIfValueOfFrameNull = (String) jListFrames.getSelectedValue();
		if (checkIfValueOfFrameNull != null){
		listOfFrames.remove(indexOfFrameToDelete);
		Collections.sort(listOfFrames);
		listofFramesInFrame = listOfFrames.toArray(new String[listOfFrames.size()]);
		updateDataAtJListFrames();
	//	System.out.println(listOfFrames);
	//	System.out.println(listofFramesInFrame);
		WriteGroupsToXMLwithProjects.addListOfFramesToProjectAtXML
		(listOfProjects, listOfFrames, listOfProjectsFileName, 
				nameOfProjectToShowFrames, listofFramesInFrame);
		}
		else JOptionPane.showMessageDialog(new JFrame(), "Please, select one of the frames", "Error",
		        JOptionPane.ERROR_MESSAGE);
		}
		
	public static void main(String args[]) {
    configuateAllApplicationAndGetData();
    fillProjectFrame();
    checkForTroublesWhileStartingGUI();
    
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new ProjectsAndFramesList().setVisible(true);
        }
    });
	}

		private static void checkForTroublesWhileStartingGUI() {
		try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ProjectsAndFramesList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ProjectsAndFramesList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ProjectsAndFramesList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ProjectsAndFramesList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
		}

		private static void fillProjectFrame() {
		GetDataFromProjectXML getGroupsFromXML = new GetDataFromProjectXML();
    	List<String> converterGroupsListFromClass = getGroupsFromXML.getOldListOfProjects(listOfProjectsFileName);
    	listOfProjects = converterGroupsListFromClass;
    	listofProjectsInFrame = listOfProjects.toArray(new String[listOfProjects.size()]);
		}

		private static void configuateAllApplicationAndGetData() {
		BaseOperations baseOperations = new BaseOperations(); 
    	String converterConfigurationFromClass = baseOperations.getConfiguration("ProjectList");
    	listOfProjectsFileName = converterConfigurationFromClass;
    		
    	converterConfigurationFromClass = baseOperations.getConfiguration("FramesList");
    	listOfFramesFileName = converterConfigurationFromClass;
		}
 
		public static String[] getListofFramesInFrame() {
		return listofFramesInFrame;
		}

		public static void setListofFramesInFrame(String[] listofFramesInFrame) {
		ProjectsAndFramesList.listofFramesInFrame = listofFramesInFrame;
		}

	// Variables declaration - do not modify//GEN-BEGIN:variables
   
		public int getIndexOfProjectToShowFrames() {
		return indexOfProjectToShowFrames;
		}

		public void setIndexOfProjectToShowFrames(int indexOfProjectToShowFrames) {
		this.indexOfProjectToShowFrames = indexOfProjectToShowFrames;
		}

		public List<String> getListOfProjectsWithOldNames() {
		return listOfProjectsWithOldNames;
		}

		public void setListOfProjectsWithOldNames(
			List<String> listOfProjectsWithOldNames) {
		this.listOfProjectsWithOldNames = listOfProjectsWithOldNames;
		}

		public String getNameOfFrameToDelete() {
		return nameOfFrameToDelete;
		}

		public void setNameOfFrameToDelete(String nameOfFrameToDelete) {
		this.nameOfFrameToDelete = nameOfFrameToDelete;
		}

	private javax.swing.JButton jButtonAddFrame;
    private javax.swing.JButton jButtonAddProject;
    private javax.swing.JButton jButtonViewFrame;
    private javax.swing.JButton jButtonEditFrame;
    private javax.swing.JButton jButtonEditProject;
    private javax.swing.JButton jButtonDeleteFrame;
    private javax.swing.JButton jButtonDeleteProject;
    private javax.swing.JButton jButtonShowFramesOfProject;
    private javax.swing.JLabel jLabelFrames;
    private javax.swing.JLabel jLabelProjects;
    @SuppressWarnings("rawtypes")
	private javax.swing.JList jListFrames;
    @SuppressWarnings("rawtypes")
	private javax.swing.JList jListProjects;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTextFieldNewProjectName;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextField jTextFieldNewFrameName;
    // End of variables declaration//GEN-END:variables
	private String nameOfFrameToDelete;
}
